package cn.tedu.store.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.tedu.store.bean.Goods;
import cn.tedu.store.service.IGoodsService;

@Controller
@RequestMapping("/goods")
public class GoodsController extends BaseController {
	@Resource(name="goodsService")
	private IGoodsService goodsService;
	
	@RequestMapping("/list.do")
	public String getGoodsListByCategoryId(
			@RequestParam("category_id") Integer categoryId,
			@RequestParam(value="order_by",required=false)Integer orderBy,
			@RequestParam(value="page",required=false) Integer page,
			ModelMap modelMap){
		List<Goods> goodsList;
		Integer goodsCount;
		String orderByStr;
		Integer pages;
		Integer countPerPage;
		if(categoryId==null || categoryId<1) {
			modelMap.addAttribute("msg", "请求参数有误");
			return "error";
		}
		if(page==null || page<1) {
			page=1;
		}
		goodsCount=goodsService.getGoodsCountByCategoryId(categoryId);
		if(orderBy==null || orderBy<0 || orderBy>=IGoodsService.ORDER_BY.length) {
			orderBy=0;
		}
		orderByStr=IGoodsService.ORDER_BY[orderBy];
		goodsService.setCountPerPage(IGoodsService.COUNT_PER_PAGE);
		goodsList=goodsService.getGoodsListByCategoryId(categoryId, orderByStr, page);
		countPerPage=goodsService.getCountPerPage();
		pages=goodsCount/countPerPage;
		pages+= pages%countPerPage==0 ? 0:1;
		modelMap.addAttribute("goodsList", goodsList);
		modelMap.addAttribute("goodsCount", goodsCount);
		modelMap.addAttribute("countPerPage", countPerPage);
		modelMap.addAttribute("pages", pages);
		modelMap.addAttribute("categoryId", categoryId);
		return "goods_list";
	}
}
